﻿#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    setWindowIcon(QIcon(":/logo/logo.ico"));
    setWindowTitle("LeftNavigationDemo");
    qDebug() << "LeftNavigationDemo Runing Version:" << QCoreApplication::applicationVersion();
    qDebug() << "LeftNavigationDemo CurrentThradId:" << QThread::currentThreadId();

    //界面管理
    my_maindesigner = new MainDesigner(this);
    my_dataanalyse = new DataAnalyse(this);
    my_systemsetting = new SystemSetting(this);
    ui->stackedWidget->addWidget(my_maindesigner);
    ui->stackedWidget->addWidget(my_dataanalyse);
    ui->stackedWidget->addWidget(my_systemsetting);

    //按钮管理
    btn_group.addButton(ui->tbtn_mainDesigner,0);
    btn_group.addButton(ui->tbtn_dataAnalyse,1);
    btn_group.addButton(ui->tbtn_systemSet,2);
    connect(&btn_group, static_cast<void (QButtonGroup::*)(int)>(&QButtonGroup::idClicked),
            ui->stackedWidget, &QStackedWidget::setCurrentIndex);
    // 设置默认选中的页面
    btn_group.button(0)->setChecked(true);
    ui->stackedWidget->setCurrentIndex(0);
    //状态栏
    lab_status1 = new QLabel(this);
    lab_status1->setText("串口状态:未连接");
    lab_status2 = new QLabel(this);
    lab_status2->setText("网口状态:未连接");
    lab_status3 = new QLabel(this);
    lab_status3->setText("status3");
    this->statusBar()->addWidget(lab_status1);
    this->statusBar()->addWidget(lab_status2);
    this->statusBar()->addWidget(lab_status3);

    //通信线程
    serial_service = new SerialPortService;
    serial_service->moveToThread(&serial_thread);
    serial_thread.start();
    connect(&serial_thread,&QThread::finished,serial_service,&QObject::deleteLater);
    //使用信号操作串口，会在线程中运行。
    connect(this,&MainWindow::sig_serialWrite,serial_service,&SerialPortService::slots_SerialWriteData);
    connect(this,&MainWindow::sig_SerialClose,serial_service,&SerialPortService::slots_CloseSerialPort);
    connect(my_maindesigner,&MainDesigner::sig_SerialWrite,serial_service,&SerialPortService::slots_SerialWriteData);

    serial_service->SetSerialInfo(my_systemsetting->GetSerialInfo().serial_name \
                                 ,my_systemsetting->GetSerialInfo().serial_baud);
}

MainWindow::~MainWindow()
{
    delete ui;
    serial_thread.quit();
    serial_thread.wait();
}

void MainWindow::closeEvent(QCloseEvent *event)
{
    QMessageBox::StandardButton button = \
        (QMessageBox::StandardButton)QMessageBox::question(this,"LeftNavigationDemo","确认退出", \
            QMessageBox::StandardButton::Yes,QMessageBox::StandardButton::No);
    if( QMessageBox::StandardButton::Yes == button ) {
        event->accept();    //默认情况下接收关闭信号，关闭窗体
    }
    else {
        event->ignore();    //忽略关闭信号,组织窗体关闭
    }
    serial_thread.quit();
    serial_thread.wait();
}

void MainWindow::on_tbtn_dataAnalyse_clicked()
{
}

